"use client"

import { InputNumber, Modal, Radio, RadioChangeEvent, Select, SelectProps } from "antd";
import { useEffect, useState } from "react";

// 定义配置选项的类型
interface MyComponentProps {
    updateCron: (cornType: string, value: string) => void;
    cronType: string;
    cronValue: string;
}

const WeekView: React.FC<MyComponentProps> = (props) => {
    const [selectedOption, setSelectedOption] = useState<string>("1");
    const [cycle01, setCycle01] = useState<number>(2);
    const [cycle02, setCycle02] = useState<number>(3);
    const [average01, setAverage01] = useState<number>(1);
    const [average02, setAverage02] = useState<number>(2);
    const [checkboxList, setCheckboxList] = useState<number[]>([]);
    // 周的选择下拉
    const [weekOptions1, setWeekOptions1] = useState<SelectProps['options']>([]);
    const [weekOptions2, setWeekOptions2] = useState<SelectProps['options']>([]);
    const [weekday, setWeekday] = useState<number>(2);

    const radioGroupStyle: React.CSSProperties = {
        display: 'flex',
        flexDirection: 'column',
    };
    const options: SelectProps['options'] = [];
    const weekNames = ["日", "一", "二", "三", "四", "五", "六",];


    if (props.cronType == 'week') {
        for (let i = 1; i <= 7; i++) {
            options.push({
                value: i,
                label: `星期${weekNames[i - 1]}`,
            });
        }
    }
    useEffect(() => {
        if (props.cronValue) {
            changeRadioValue(props.cronValue)
        }
    }, [props.cronValue])
    useEffect(() => {
        if (cycle01 >= cycle02) {
            setCycle02(cycle01 + 1)
        }
    }, [cycle01])

    useEffect(() => {
        if (props.cronType == 'week') {
            const newWeekOption1 = []
            const newWeekOption2 = []
            for (let i = 1; i <= 7; i++) {
                newWeekOption1.push(
                    {
                        value: i,
                        label: `星期${weekNames[i - 1]}`,
                        disabled: i == 7||i>=cycle02 ? true : false,
                    }
                )
                newWeekOption2.push(
                    {
                        value: i,
                        label: `星期${weekNames[i - 1]}`,
                        disabled: cycle01 >= i ? true : false,
                    }
                )
            }
            setWeekOptions1(newWeekOption1)
            setWeekOptions2(newWeekOption2)
        }
        if (selectedOption === "3") {
            props.updateCron(props.cronType, `${cycle01}-${cycle02}`);
        }
    }, [cycle01, cycle02, selectedOption]);
    const changeRadioValue = (value: string) => {
        if (value === '*') {
            setSelectedOption("1")
        } else if (value === '?') {
            setSelectedOption("2")
        } else if (value.indexOf('-') > -1) {
            const indexArr = value.split('-')
            setCycle01(Number(indexArr[0]))
            setCycle02(Number(indexArr[1]))
            setSelectedOption("3")
        } else if (value.indexOf('#') > -1) {
            const indexArr = value.split('#')
            setAverage01(Number(indexArr[1]))
            setAverage02(Number(indexArr[0]))
            setSelectedOption("4")
        } else if (value.indexOf('L') > -1) {
            const indexArr = value.split('L')
            setWeekday(Number(indexArr[0]))
            setSelectedOption("5")
        } else {
            setCheckboxList([...new Set(value.split(',').map(item => Number(item)))])
            setSelectedOption("6")
        }
    }

    const handleSelectChange = (value: number[]) => {
        if (value.length < 1) return;
        setCheckboxList(value);
        if (value.length > 0) {
            props.updateCron(props.cronType, value.join(','));
        } else {
            props.updateCron(props.cronType, '*');
        }
    };

    const handleCycle01Change = (value: number | null) => {
        if (value !== null) {
            setCycle01(value);
        }
    };

    const handleCycle02Change = (value: number | null) => {
        if (value !== null) {
            setCycle02(value);
        }
    };

    const handleAverage01Change = (value: number | null) => {
        if (value !== null) {
            setAverage01(value);
            if (selectedOption === "4") {
                props.updateCron(props.cronType, `${value}#${average02}`);
            }
        }
    };

    const handleAverage02Change = (value: number | null) => {
        if (value !== null) {
            setAverage02(value);
            if (selectedOption === "4") {
                props.updateCron(props.cronType, `${value}#${average01}`);
            }
        }
    };
    const handleWeekdayChange = (value: number | null) => {
        if (value !== null) {
            setWeekday(value);
            if (selectedOption === "5") {
                props.updateCron(props.cronType, `${value}L`);
            }
        }
    };

    const onRadioChange = (e: RadioChangeEvent) => {
        const selectedValue = e.target.value;
        setSelectedOption(selectedValue);

        switch (selectedValue) {
            case "1":
                props.updateCron(props.cronType, '*');
                break;
            case "2":
                props.updateCron(props.cronType, '?');
                break;
            case "3":
                props.updateCron(props.cronType, `${cycle01}-${cycle02}`);
                break;
            case "4":
                props.updateCron(props.cronType, `${average02}#${average01}`);
                break;
            case "5":
                if (!weekday) {
                    setWeekday(2)
                }
                props.updateCron(props.cronType, `${weekday}L`);
                break;
            case "6":
                if (checkboxList.length === 0) {
                    const defaultValues = [2];
                    setCheckboxList(defaultValues);
                    props.updateCron(props.cronType, defaultValues.join(','));
                } else {
                    props.updateCron(props.cronType, checkboxList.join(','));
                }
                break;

        }
    };

    // 阻止事件冒泡的工具函数
    const preventBubble = (e: React.MouseEvent) => {
        e.stopPropagation();
    };

    return (
        <div >
            <Radio.Group
                value={selectedOption}
                style={radioGroupStyle}
                onChange={onRadioChange}
            >
                <Radio value="1" style={{ padding: '8px 5px', borderRadius: '6px' }}>
                    秒，允许的通配符[, - * /]
                </Radio>
                {(props.cronType == 'day' || props.cronType == 'week') && <Radio value="2" style={{ padding: '8px 5px', borderRadius: '6px' }}>
                    不指定
                </Radio>}

                <Radio value="3" style={{ padding: '8px 5px', borderRadius: '6px' }}>
                    <div
                        onClick={preventBubble}
                    >
                        周期从
                        {props.cronType == 'week' && <span>
                            <Select
                                onClick={(e) => { e.preventDefault(); }}
                                placeholder="可多选"
                                value={cycle01}
                                onChange={handleCycle01Change}
                                style={{ minWidth: "100px", marginLeft: '20px' }}
                                options={weekOptions1}
                                optionRender={(option) => (
                                    <div>{option.data.label}</div>
                                )}
                                size="small"
                            />
                            到
                            <Select
                                onClick={(e) => { e.preventDefault(); }}
                                allowClear
                                placeholder="可多选"
                                value={cycle02}
                                onChange={handleCycle02Change}
                                style={{ minWidth: "100px", marginLeft: '20px' }}
                                options={weekOptions2}
                                size="small"
                            /></span>}
                        {props.cronType !== 'week' && <span>
                            <InputNumber
                                value={cycle01}
                                min={0}
                                max={58}
                                style={{ margin: '0px 10px' }}
                                onChange={handleCycle01Change}
                                size="small"
                            />
                            到
                            <InputNumber
                                value={cycle02}
                                min={cycle01 + 1}
                                max={59}
                                style={{ margin: '0px 10px' }}
                                onChange={handleCycle02Change}
                                size="small"
                            /></span>}
                        秒
                    </div>
                </Radio>

                <Radio value="4" style={{ padding: '8px 5px', borderRadius: '6px' }}>

                    <div
                        onClick={preventBubble}>
                        第
                        <InputNumber
                            value={average01}
                            min={1}
                            max={4}
                            style={{ margin: '0px 10px' }}
                            onChange={handleAverage01Change}
                            size="small"
                        />周的<Select
                            onClick={(e) => { e.preventDefault(); }}
                            allowClear
                            placeholder="选择"
                            value={average02}
                            onChange={handleAverage02Change}
                            style={{ minWidth: "100px", marginLeft: '20px' }}
                            options={options}
                            size="small"
                        />
                    </div>
                </Radio>
                <Radio value="5" style={{ padding: '8px 5px', borderRadius: '6px' }}>
                    <div
                        onClick={preventBubble}>
                        本月最后一个
                        <Select
                            onClick={(e) => { e.preventDefault(); }}
                            placeholder="可多选"
                            value={weekday}
                            onChange={handleWeekdayChange}
                            style={{ minWidth: "100px", marginLeft: '20px' }}
                            options={options}
                            size="small"
                        />
                    </div>
                </Radio>
                <Radio value="6" style={{ padding: '8px 5px', borderRadius: '6px' }}>
                    <div
                        onClick={preventBubble}>
                        指定
                        <Select
                            onClick={(e) => { e.preventDefault(); }}
                            mode="multiple"
                            allowClear
                            placeholder="可多选"
                            value={checkboxList}
                            onChange={handleSelectChange}
                            maxCount={10}
                            style={{ minWidth: "100px", marginLeft: '20px' }}
                            options={options}
                            size="small"
                        />
                    </div>
                </Radio>

            </Radio.Group>
        </div>
    );
};

export default WeekView;